#include <sys/select.h>
#include <unistd.h>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <boost/thread.hpp>
#include <boost/shared_ptr.hpp>
#include "session.hpp"
#include "routingindex.hpp"
#include "query.hpp"

class Plumber
{
public:
    Plumber(int port, RoutingIndex r);
    bool start();
    bool stop();
private:
    typedef boost::shared_ptr<Session> spointer;
    static const int MAX_EVENTS  = 64;
    static const int WINDOWS_SIZE = 100000;
    void workLoop_();
    bool setUpServerSocket_();
    void handleAccept_();
    void handleRequest_(std::string, struct timeval);
    void updateQueries_(struct timeval);
    std::string pickSetValue(Query q);

    bool sendPackets(CmdHeader header, std::vector<std::string> args, std::vector<std::string> hosts);

    int port_;
    int masterSocket_;

    int efd_;

    boost::thread *t_;

    std::map <std::string, spointer> clients_;
    std::vector <char*> names_;
    std::map <std::string, Query> queries_;
    RoutingIndex index_;
};
